package com.ebocy.hammer.game.service;

import java.util.List;
import java.util.Map;

import com.ebocy.hammer.core.GameCache;
import com.ebocy.hammer.core.constants.ErrorCode;
import com.ebocy.hammer.core.domain.GamePlayer;
import com.ebocy.hammer.core.domain.GamePlayerItem;
import com.ebocy.hammer.core.domain.Shop;
import com.ebocy.hammer.core.message.AbstractS2CMessage;
import com.ebocy.hammer.core.message.S2CErrorCode;
import com.ebocy.hammer.core.service.GamePlayerService;
import com.ebocy.hammer.core.service.ItemService;
import com.ebocy.hammer.core.util.Util;
import com.ebocy.hammer.game.message.C2SItemChange;
import com.ebocy.hammer.game.message.C2SPlayerRole;
import com.ebocy.hammer.game.message.C2SShopOperation;
import com.ebocy.hammer.game.message.S2CItemChange;
import com.ebocy.hammer.game.message.S2CPlayerRole;
import com.ebocy.hammer.game.message.S2CShopOperation;

/**
 * @author Qingrong Hou Jun 14, 2012
 */
public class GameServerService {
	private static ItemService itemService = null;
	private static ShopService shopService = null;
	private static GamePlayerService gamePlayerService = null;

	private GameServerService() {
		if (itemService == null) {
			itemService = ItemService.getInstance();
		}
		if (shopService == null) {
			shopService = ShopService.getInstance();
		}
		if (gamePlayerService == null) {
			gamePlayerService = GamePlayerService.getInstance();
		}

	}

	public static GameServerService getInstance() {
		return SingletonClassInstance.instance;
	}

	private static class SingletonClassInstance {
		private static final GameServerService instance = new GameServerService();
	}

	/**
	 * 商店操作,购买物品
	 * 
	 * @param gamePlayer
	 *            玩家信息
	 * @param c2SShop
	 *            物品参数
	 */
	public void shopOperation(GamePlayer gamePlayer, C2SShopOperation c2SShop) {
		AbstractS2CMessage message = null;
		// 获取商店物品
		Shop shopItem = shopService.findShopItem(c2SShop.getWaresId());
		if (shopItem != null) {
			// 获取商店物品Id
			int itemId = shopService.findShopItemId(shopItem, ",");
			// 获取商店物品售价
			int price = shopService.findShopPrice(shopItem, ";", c2SShop.getIndex(), ",");
			// 期限
			short effectiveTime = shopService.findShopExpires(shopItem, ";", c2SShop.getIndex(), ",");
			// 获取商店物品类型
			byte kind = shopService.findShopKind(shopItem);
			// 获取币种 0为金币,1为e币
			byte currency = shopService.findShopCurrency(shopItem);
			if (currency == 0) {// 金币
				int playerGold = gamePlayer.getGold();
				if (playerGold - price < 0) {// 金币不够购买
					message = new S2CErrorCode(ErrorCode.SHOP_ERROR_GOLD);
				} else {
					// 给玩家增加物品
					GamePlayerItem gamePlayerItem = itemService.addItem(gamePlayer.getGamePlayerId(), itemId, 0, kind, effectiveTime, 0);

					// 更新玩家背包信息
					List<GamePlayerItem> knapsack = gamePlayer.getKnapsack();
					knapsack.add(gamePlayerItem);
					gamePlayer.setKnapsack(knapsack);

					// 扣钱
					gamePlayer.setGold(playerGold - price);
					Map<?, ?> value = Util.toMap(GamePlayer.GOLD, gamePlayer.getGold());
					gamePlayerService.updateGamePlayer(gamePlayer, value);
					message = new S2CShopOperation(gamePlayerItem.getGamePlayerItemId());
				}
			} else {// e币
				int playerEgold = gamePlayer.geteGold();
				if (playerEgold - price < 0) {// e币不够购买
					message = new S2CErrorCode(ErrorCode.SHOP_ERROR_EGOLD);
				} else {
					// 给玩家增加物品
					GamePlayerItem gamePlayerItem = itemService.addItem(gamePlayer.getGamePlayerId(), itemId, 0, kind, effectiveTime, 0);

					// 更新玩家背包信息
					List<GamePlayerItem> knapsack = gamePlayer.getKnapsack();
					knapsack.add(gamePlayerItem);
					gamePlayer.setKnapsack(knapsack);

					// 扣钱
					gamePlayer.seteGold(playerEgold - price);
					Map<?, ?> value = Util.toMap(GamePlayer.EGOLD, gamePlayer.geteGold());
					gamePlayerService.updateGamePlayer(gamePlayer, value);
					message = new S2CShopOperation(gamePlayerItem.getGamePlayerItemId());
				}
			}
		} else {
			message = new S2CErrorCode(ErrorCode.ITEM_NOT_FOUNT);
			gamePlayer.sendMessage(message);
		}
		gamePlayer.sendMessage(message);
	}

	/**
	 * 物品更换操作
	 */
	public void itemChange(GamePlayer gamePlayer, C2SItemChange c2SItemChange) {
		// 获取物品详细
		GamePlayerItem gamePlayerItem = itemService.findGamePlayerItem(c2SItemChange.getGamePlayerItemId());
		if (gamePlayerItem != null) {
			int kind = gamePlayerItem.getKind();
			switch (kind) {
			case 1:// 锤子
				hammerAndRoleChange(gamePlayer, kind, gamePlayerItem);
				break;
			case 2:// 道具
				itemChange(gamePlayer, kind, gamePlayerItem, c2SItemChange);
				break;
			case 3:// 形象
				hammerAndRoleChange(gamePlayer, kind, gamePlayerItem);
				break;
			}
		} else {
			// 物品未找到
			AbstractS2CMessage message = new S2CErrorCode(ErrorCode.ITEM_NOT_FOUNT);
			gamePlayer.sendMessage(message);
		}
	}

	// 更换道具
	private void itemChange(GamePlayer gamePlayer, int kind, GamePlayerItem gamePlayerItem, C2SItemChange c2SItemChange) {
		AbstractS2CMessage message = null;
		if (c2SItemChange.getKey() <= (short) 4) {
			List<GamePlayerItem> itemList = gamePlayer.getKnapsack();
			for (GamePlayerItem item : itemList) {
				// 遍历背包道具
				if (item.getKind() == kind) {
					// 已有道具
					if (item.getKey() == c2SItemChange.getKey()) {
						item.setKey(0);// 卸下已装备道具
						Map<?, ?> values = Util.toMap(GamePlayerItem.KEY, item.getKey());
						itemService.updateItem(item, values);
						break;
					}
				}
			}
			for (GamePlayerItem item : itemList) {
				// 遍历背包道具
				if (item.getKind() == kind) {
					// 查找需要装备的道具
					if (item.getGamePlayerItemId() == gamePlayerItem.getGamePlayerItemId()) {
						item.setKey(c2SItemChange.getKey());// 装备道具
						// 首次装备
						if (item.getCreateTime() == 0) {
							item.setCreateTime(System.currentTimeMillis());
							Map<?, ?> values = Util.toMap(GamePlayerItem.KEY, item.getKey(), GamePlayerItem.CREATETIME, item.getCreateTime());
							itemService.updateItem(item, values);
							message = new S2CItemChange(item.getCreateTime());
						} else {
							Map<?, ?> values = Util.toMap(GamePlayerItem.KEY, item.getKey());
							itemService.updateItem(item, values);
							message = new S2CItemChange(0);
						}
						break;
					}
				}
			}
			gamePlayer.setKnapsack(itemList);
		} else {
			// 超出范围
			message = new S2CErrorCode(ErrorCode.ITEM_CHANGE_ERROR_KEY);
		}
		gamePlayer.sendMessage(message);
	}

	// 更换锤子或形象
	private void hammerAndRoleChange(GamePlayer gamePlayer, int kind, GamePlayerItem gamePlayerItem) {
		List<GamePlayerItem> itemList = gamePlayer.getKnapsack();
		AbstractS2CMessage message = null;
		for (GamePlayerItem item : itemList) {
			// 遍历背包锤子或形象
			if (item.getKind() == kind) {
				// 已有装备锤子或形象
				if (item.getKey() == 1) {
					item.setKey(0);// 卸下已装备锤子或形象
					Map<?, ?> values = Util.toMap(GamePlayerItem.KEY, item.getKey());
					itemService.updateItem(item, values);
					break;
				}
			}
		}
		for (GamePlayerItem item : itemList) {
			// 遍历背包锤子或形象
			if (item.getKind() == kind) {
				// 查找需要装备的锤子或形象
				if (item.getGamePlayerItemId() == gamePlayerItem.getGamePlayerItemId()) {
					item.setKey(1);// 装备锤子或形象
					if (item.getCreateTime() == 0) {
						item.setCreateTime(System.currentTimeMillis());
						Map<?, ?> values = Util.toMap(GamePlayerItem.KEY, item.getKey(), GamePlayerItem.CREATETIME, item.getCreateTime());
						itemService.updateItem(item, values);
						message = new S2CItemChange(item.getCreateTime());
					} else {
						Map<?, ?> values = Util.toMap(GamePlayerItem.KEY, item.getKey());
						itemService.updateItem(item, values);
						message = new S2CItemChange(0);
					}
					// 更新用户形象字段
					if (kind == 3) {
						gamePlayer.setRoleImage(item.getItemId());
						gamePlayerService.updateGamePlayer(gamePlayer, Util.toMap(GamePlayer.ROLEIMAGE, item.getItemId()));
					}
					// 更新用户锤子字段
					if (kind == 1) {
						gamePlayer.setHammerId(item.getItemId());
						gamePlayerService.updateGamePlayer(gamePlayer, Util.toMap(GamePlayer.HAMMERID, item.getItemId()));
					}
					break;
				}
			}
		}
		gamePlayer.setKnapsack(itemList);
		gamePlayer.sendMessage(message);
	}

	/**
	 * 用户选择形象
	 */
	public void changeRole(GamePlayer gamePlayer, C2SPlayerRole c2SPlayerRole) {
		initPlayerRole(gamePlayer, c2SPlayerRole.getRoleId());
	}

	// 用户形象初始化
	private void initPlayerRole(GamePlayer gamePlayer, short roleId) {
		try {
			// 获取用户背包
			List<GamePlayerItem> knapsack = gamePlayer.getKnapsack();
			// 初始化形象,种类=3
			GamePlayerItem gamePlayerItem = itemService.addItem(gamePlayer.getGamePlayerId(), roleId, 1, (byte) 3, (short) -1, System.currentTimeMillis());
			knapsack.add(gamePlayerItem);
			// 更新用户背包
			gamePlayer.setKnapsack(knapsack);
			// 返回形象id
			AbstractS2CMessage message = new S2CPlayerRole(gamePlayerItem.getGamePlayerItemId());
			gamePlayer.sendMessage(message);
			gamePlayer.setRoleImage(roleId);
			gamePlayerService.updateGamePlayer(gamePlayer, Util.toMap(GamePlayer.ROLEIMAGE, roleId));
		} catch (Exception e) {
			AbstractS2CMessage message = new S2CErrorCode(ErrorCode.CHOOSE_ROLE_ERROR);
			gamePlayer.sendMessage(message);
		}
	}

	// /**
	// * 退出游戏
	// */
	// public void exitGame(GamePlayer gamePlayer) {
	// if (gamePlayer != null) {
	// // 从缓存中去掉玩家记录
	// GameCache.getInstance().removeGamePlayer(gamePlayer);
	//
	// Room room = GameCache.room4V4Map.get(gamePlayer.getRoomId());
	// if (room != null) {
	// // 通知其他玩家
	// AbstractS2CMessage message = new
	// S2CExitGameMessage(gamePlayer.getGamePlayerId());
	// gamePlayer.sendMessageToRoomOther(message);
	//
	// // 从房间中退出
	// room.members.remove(gamePlayer.getGamePlayerId());
	// }
	// }
	// }

}
